import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as SellChanceMainAction from '../actions/sellChanceMain'

import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'
import WeaCrmTab from './weaCrmTab' 
import WeaDropdown from './weaCrmDropdown';
import ViewContactLog from './data/ViewContactLog.js'
import ViewContacter from './data/ViewContacter.js'
import WeaRightLeftLayout from './weaCrmRightLeft'

import SetTagModal from './data/SetTagModal.js'
import CardManage from  './card/cardManage.js'

import { WeaTable } from 'comsRedux'
 const WeaTableAction = WeaTable.action;
import WeaFormmodeTop from './WeaFormmodeTop'
import {
    WeaReqTop ,
    WeaTab,
    WeaSearchGroup,
    WeaRightMenu,
    WeaPopoverHrm ,
} from 'ecCom'

import {WeaErrorPage,WeaTools,WeaSelect,WeaBrowser} from 'ecCom'

import {Button,Form,Modal,message,Select,DatePicker,Menu,Rate, Dropdown, Icon,Tabs,Tooltip,Col,Spin} from 'antd'
const Option = Select.Option; 
const createForm = Form.create;
const FormItem = Form.Item;
const MonthPicker = DatePicker.MonthPicker;
const TabPane = Tabs.TabPane;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'

import PropTypes from 'react-router/lib/PropTypes'
import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class SellChanceMain extends React.Component {
    constructor(props) {
		super(props);
		_this = this;
    }
    componentDidMount() {
    	  const {actions} = this.props;
          actions.setNowRouterCmpath('sellChanceMain');

          actions.initDatas();   //初始化高级搜索
          actions.sellChanceTabs();  //tab栏
          actions.sellChanceStatusAndHrm();   //状态，人员
          actions.doSearch();   //列表
          actions.getSellChanceTagsList({type:"sellchance"}); //自定义标签
          actions.getContactLogs();
          actions.getRemindCount();
    }
    componentWillReceiveProps(nextProps) {

    }
    shouldComponentUpdate(nextProps,nextState) {
        return !is(this.props.title,nextProps.title)||
        !is(this.props.dataKey,nextProps.dataKey)||
        !is(this.props.detailTabKey,nextProps.detailTabKey)||
        !is(this.props.conditioninfo,nextProps.conditioninfo)||
        !is(this.props.loading,nextProps.loading)||
         !is(this.props.comsWeaTable,nextProps.comsWeaTable)||
        !is(this.props.showSearchAd,nextProps.showSearchAd)||
        !is(this.props.orderFields,nextProps.orderFields)||
        !is(this.props.tabDatas,nextProps.tabDatas)||
        !is(this.props.sellChanceStatus,nextProps.sellChanceStatus)||
        !is(this.props.hrmList,nextProps.hrmList)||
        !is(this.props.tagDatas,nextProps.tagDatas)||
        !is(this.props.viewTypeList,nextProps.viewTypeList)||
        !is(this.props.istorefresh,nextProps.istorefresh)||
        !is(this.props.detailTabDatas,nextProps.detailTabDatas)||
        !is(this.props.rightTabKey,nextProps.rightTabKey)||
        !is(this.props.selectValue,nextProps.selectValue)||
        !is(this.props.contactLogs,nextProps.contactLogs)||
        !is(this.props.cardloading,nextProps.cardloading)||
        !is(this.props.contacterCard,nextProps.contacterCard)||
        !is(this.props.showRight,nextProps.showRight)||
        !is(this.props.rightInfos,nextProps.rightInfos)||
        !is(this.props.remindCount,nextProps.remindCount)
    }
    componentWillUnmount(){
    	// const {actions,isClearNowPageStatus} = this.props;
        // actions.unmountClear(isClearNowPageStatus);
        // actions.isClearNowPageStatus(false);
    }
    render() {
        let that = this;
        const {loading,actions,dataKey,title,conditioninfo,detailTabKey,comsWeaTable,tabDatas,
            sellChanceStatus,tagDatas,detailTabDatas,rightTabKey,selectValue,contactLogs,contacterCard,cardloading,showRight,rightInfos} = this.props;
        const name = dataKey ? dataKey.split('_')[0] : 'init';
        const loadingTable = comsWeaTable.get(name).toJS().loading;
        const selectedRowKeys = comsWeaTable.get('selectedRowKeys');
        const { getFieldProps } = this.props.form;
        return (
            <div>
                <WeaPopoverHrm  />
               	<WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                 <WeaFormmodeTop
                	title={title}
                	loading={loading || loadingTable}
                	icon={<i className='icon-coms-crm' />}
                    tabDatas={tabDatas.toJS()}
                    selectedKey={detailTabKey}
                    onChange={this.changeData.bind(this)}
                	iconBgcolor='#96358a'
                	buttons={this.getButtons()}
                	buttonSpace={10}
                	showDropIcon={true}
                	dropMenuDatas={this.getRightMenu()}
                >
            
                    <div className="contacter-hrm-detail height100" >
                        <WeaRightLeftLayout  defaultShowLeft={false} leftCom={this.getSellChanceTable()} >
                        {
                            !showRight &&
                            <div className="crm-right-tab">
                                <div className="sellchancemain-right-top">
                                    <WeaSelect 
                                        value={selectValue}
                                        options={[{key: "1", selected: true, showname:"近一月"},
                                            {key: "2", selected: false, showname: "近三月"},
                                            {key: "3", selected: false, showname: "近半年"},
                                            {key: "4", selected: false, showname: "近一年"},
                                            {key: "5", selected: false, showname: "全部"}]} 
                                        onChange={this.dateSelectChange.bind(this)}
                                    />
                                </div>
                                <WeaTab
                                    selectedKey={rightTabKey}
                                    datas={detailTabDatas.toJS()}
                                    keyParam='key'
                                    onChange={this.changeRightTab.bind(this)} />
                                    
                                { 
                                    rightTabKey=="1" && 
                                    <Spin spinning={cardloading} >
                                        <ViewContactLog data ={contactLogs}/>
                                    </Spin>
                                }
                                { 
                                    rightTabKey=="2" && 
                                    <Spin spinning={cardloading} >
                                        <ViewContacter data={contacterCard}/>
                                    </Spin>
                                }
                            </div>
                        }
                        {
                            showRight &&
                            <CardManage  
                                paramsData={{from:"sellchance",fromType:"sellchance",chanceid:rightInfos.get('sellchanceId'),customerId:rightInfos.get('customerId')}} 
                                rightInfos={rightInfos} 
                                type="sellchance"
                            />
                        }  
                        </WeaRightLeftLayout>
                    </div>
               </WeaFormmodeTop>
                </WeaRightMenu>
                <SetTagModal ref="setTagModal" data={tagDatas.toJS()} actions={actions} type={'sellchance'}/>
            </div>
        )
    }
    onRightMenuClick(key){
    	 const {actions,comsWeaTable,dataKey} = this.props;
    	// const selectedRowKeys = comsWeaTable.get('selectedRowKeys');
    	if(key == '0'){
    		actions.doSearch();
    		actions.setShowSearchAd(false)
    	}
    	if(key == '1'){
    		// actions.batchSubmitClick({checkedKeys:`${selectedRowKeys.toJS()}`})
    	}
    }
    getRightMenu(){
    	let btns = [];   
    	btns.push({
    		icon: <i className='icon-coms-Collection'/>,
    		content:'收藏'
    	});
        btns.push({
            icon: <i className='icon-coms-help'/>,
            content:'帮助',
        })
    	return btns
    }
     getButtons() {
        const {remindCount} = this.props;
        // const {router} = this.context;
        let btnArr = [];
       btnArr.push(<Tooltip placement="bottom" title={"新建商机"}><span onClick={()=>crmOpenSPA4Single('/main/crm/addSellChance')}><i className="crm-hover-icon icon-crm-sellchance" style={{fontSize:"20px"}}/></span></Tooltip>);
       btnArr.push(<Tooltip placement="bottom" title={"客户联系提醒"}><span onClick={()=>crmOpenSPA4Single('/main/crm/birthday')}><Icon className="crm-hover-icon" type="notification" style={{fontSize:"16px"}}/><span style={{color:"#2db7f5"}}>{"("+remindCount+")"}</span></span></Tooltip>);
        return btnArr
    }
     changeData(key){
         const {actions,istorefresh} = this.props;
        actions.setSellChanceTabKey(key,istorefresh);
    }
     getSearchs() {
    	const { conditioninfo } = this.props;
        const { getFieldProps } = this.props.form;
		let group = [];
		conditioninfo.toJS().map(c =>{
			let items = [];
			c.items.map(field => {
                if(field.formItemType == "SELECT_BROWSER"){
                    items.push({
                        com:(<FormItem
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}
                            className="select-browser">
                            <Col span={10} className="select-wrapper" >
                                <WeaSelect {...getFieldProps(field.domkey[0])} options= {field.options}/>
                            </Col>
                            <Col span={14} style={{paddingLeft: 10}}>
                                <WeaBrowser {...field.selectLinkageDatas.browserConditionParam} 
                                showDropMenu={field.selectLinkageDatas.showDropMenu} 
                                 {...getFieldProps(field.selectLinkageDatas.domkey[0])} />
                            </Col>
                            </FormItem>),
                        colSpan:1
                    })
                }else{
                    items.push({
                        com:(<FormItem
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}>
                                { WeaTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field)}
                            </FormItem>),
                        colSpan:1
                    })
                }
			});
			group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
		});
		return group
    }
    getSellChanceTable(){
         const {searchParamsAd,actions,dataKey,showSearchAd,orderFields} = this.props;
         return (
             <div>
                     <WeaCrmTab
                        buttonsAd={this.getTabButtonsAd()}
                    	searchType={['base','advanced']}
                    	 searchsBaseValue={searchParamsAd.get('subject')}
                         setShowSearchAd={bool=>{actions.setShowSearchAd(bool)}}
                         hideSearchAd={()=> actions.setShowSearchAd(false)}
                         searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
                         showSearchAd={showSearchAd}
                         selectGroups={this.getSelectGroups()}
                         onSearch={v=>{actions.doSearch()}}
                         onSearchChange={v=>{actions.saveOrderFields({...orderFields.toJS(),...{subject:{name:'subject',value:v}}})}}
                         hasDropMenu={true}
                        />
                         <WeaTable 
                            sessionkey={dataKey}
                            hasOrder={true}
                            needScroll={true}
                            getColumns = {columns=>{ 
                                let newcol = [].concat(columns);
                                if(newcol.length>0){
                                    newcol[0].render = (text, record,index) => (<div className="crm-mine-customer-list" onClick={()=>{this.viewSellChanceDetail(record.randomFieldId)} }>{text}</div> )
                                    newcol[1].render = (text, record,index) => {
                                       return  <span dangerouslySetInnerHTML={{__html:record.createrspan}}></span>
                                    }
                                    newcol[2].render = (text, record,index) => (<span><Rate count={1}  value={text} onChange={text=>{this.focusOnClick(record.important,record.randomFieldId)}} /></span> )
                                }
                                return newcol}}
                    	/>
                        
             </div>
         )
    }
    getSelectGroups(){
        const {sellChanceStatus,hrmList,tagDatas,viewTypeList,istorefresh,detailTabKey}  =this.props;
        const {actions,dataKey, comsWeaTable,} = this.props;
        const sellChanceStatus1 = sellChanceStatus.toJS();
        const hrmList1 = hrmList.toJS();
       const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
       const tableNow = comsWeaTable.get(tablekey);
       const selectedRowKeys = tableNow.get('selectedRowKeys');
        let that = this;
       const tabBtns = (function(){
           if(hrmList1.length>0 && detailTabKey =="my"){
            return  <Tabs defaultActiveKey="">
                <TabPane tab={
                    <WeaDropdown 
                        keyValue="creater_str" 
                        defaultValue={hrmList1[0].name} 
                        type="tree" datas={hrmList1} 
                        onChange={that.selectChange.bind(that)}
                        hrmListChange={that.hrmListChange.bind(that)}
                    />  
                } key="1"></TabPane>
                <TabPane tab={
                    <WeaDropdown keyValue="containsSub" defaultValue={viewTypeList.toJS()[0].name} type="select" datas={viewTypeList.toJS()} onChange={that.selectChange.bind(that)}/>                
                } key="2"></TabPane> 
                <TabPane tab={
                    <WeaDropdown keyValue="sellstatusid_str" defaultValue="商机状态" type="select" datas={sellChanceStatus1} onChange={that.selectChange.bind(that)}/>
                } key="3"></TabPane>
                <TabPane tab={
                    <WeaDropdown keyValue="predate_str" defaultValue="销售预期" type="time" datas={[]} onChange={that.selectChange.bind(that)}/>
                } key="4"></TabPane>
                <TabPane tab={
                    <WeaDropdown keyValue="preyield_str" defaultValue="预期收益" type="select" datas={[{name: "全部",  id: "",},{name: "0-5万",  id: "0"},{name: "5-10万",  id: "1"},{name: "10-20万",  id: "2"},{name: "20-50万",  id: "3"},{name: "50-100万",  id: "4"},{name: "100万以上",  id: "5"}]} onChange={that.selectChange.bind(that)}/>
                } key="5"></TabPane>
                <TabPane tab={
                    <WeaDropdown keyValue="probability_str" defaultValue="可能性" type="select" datas={[{name: "全部",  id: "",},{name: "0-30%",  id: "0"},{name: "30%-50%",  id: "1"},{name: "50%-70%",  id: "2"},{name: "70%-90%",  id: "3"},{name: "90%以上",  id: "4"}]} onChange={that.selectChange.bind(that)}/>
                } key="6"></TabPane>
                <TabPane tab={
                    <WeaDropdown keyValue="contactTime_str" defaultValue="联系时间" type="select" datas={[{name: "全部",  id: "",},{name: "三天未联系",  id: "0"},
                        {name: "一周未联系",  id: "1"},{name: "两周未联系",  id: "2"},
                        {name: "一月未联系",  id: "3"},{name: "三月未联系",  id: "4"},
                        {name: "半年未联系",  id: "5"},{name: "一年未联系",  id: "6"},
                        {name: "无联系记录",  id: "11"},{name: "今天联系",  id: "7"},
                        {name: "近一周联系",  id: "8"},{name: "近一月联系",  id: "9"},{name: "近三月联系",  id: "10"}
                ]} onChange={that.selectChange.bind(that)}/>
                } key="7"></TabPane>
                <TabPane tab={
                    <WeaDropdown 
                        defaultValue="标签" 
                        type="tag" 
                        datas={tagDatas.toJS()} 
                        selectKeys={`${selectedRowKeys.toJS()}`} 
                        markTagsTo={that.markTagsTo.bind(that)}
                        markToCustomTag={that.markToCustomTag.bind(that)}
                        setting={that.setting.bind(that)}
                    />
                } key="8"></TabPane>
            </Tabs>
           }else{
               return  <Tabs defaultActiveKey="">
               <TabPane tab={
                   <WeaDropdown keyValue="sellstatusid_str" defaultValue="商机状态" type="select" datas={sellChanceStatus1} onChange={that.selectChange.bind(that)}/>
               } key="3"></TabPane>
               <TabPane tab={
                    <WeaDropdown keyValue="predate_str" defaultValue="销售预期" type="time" datas={[]} onChange={that.selectChange.bind(that)}/>
                } key="4"></TabPane>
                <TabPane tab={
                    <WeaDropdown keyValue="preyield_str" defaultValue="预期收益" type="select" datas={[{name: "全部",  id: "",},{name: "0-5万",  id: "0"},{name: "5-10万",  id: "1"},{name: "10-20万",  id: "2"},{name: "20-50万",  id: "3"},{name: "50-100万",  id: "4"},{name: "100万以上",  id: "5"}]} onChange={that.selectChange.bind(that)}/>
                } key="5"></TabPane>
                <TabPane tab={
                    <WeaDropdown keyValue="probability_str" defaultValue="可能性" type="select" datas={[{name: "全部",  id: "",},{name: "0-30%",  id: "0"},{name: "30%-50%",  id: "1"},{name: "50%-70%",  id: "2"},{name: "70%-90%",  id: "3"},{name: "90%以上",  id: "4"}]} onChange={that.selectChange.bind(that)}/>
                } key="6"></TabPane>
                <TabPane tab={
                    <WeaDropdown keyValue="contactTime_str" defaultValue="联系时间" type="select" datas={[{name: "全部",  id: "",},{name: "三天未联系",  id: "0"},
                        {name: "一周未联系",  id: "1"},{name: "两周未联系",  id: "2"},
                        {name: "一月未联系",  id: "3"},{name: "三月未联系",  id: "4"},
                        {name: "半年未联系",  id: "5"},{name: "一年未联系",  id: "6"},
                        {name: "无联系记录",  id: "11"},{name: "今天联系",  id: "7"},
                        {name: "近一周联系",  id: "8"},{name: "近一月联系",  id: "9"},{name: "近三月联系",  id: "10"}
                ]} onChange={that.selectChange.bind(that)}/>
                } key="7"></TabPane>
                <TabPane tab={
                    <WeaDropdown 
                        defaultValue="标签" 
                        type="tag" 
                        datas={tagDatas.toJS()} 
                        selectKeys={`${selectedRowKeys.toJS()}`} 
                        markTagsTo={that.markTagsTo.bind(that)}
                        markToCustomTag={that.markToCustomTag.bind(that)}
                        setting={that.setting.bind(that)}
                    />
                } key="8"></TabPane>
           </Tabs>
           }
            
       })() 
        return tabBtns
    }
    hrmListChange(arr){
        const {actions} = this.props;
        actions.saveHrmList(arr);
    }
    selectChange(obj){
        const {actions,orderFields} = this.props;
        actions.saveOrderFields({...orderFields.toJS(),...obj});
         actions.doSearch();
        actions.saveSelectValue("1");
        actions.setRightTabKey("1");
    }
    
    viewSellChanceDetail =(id) =>{
        const {actions} = this.props;
        actions.getSellChanceDetail(id);
    }
    focusOnClick=(num,id)=>{  //点击星星
        let flag =  1;
        if(num=="1"){flag = 0}
        this.markTagsTo(flag,id);
    }
    markTagsTo(i,key){   // 重要  取消重要
        const {actions} = this.props;
        actions.isMarkToImportant({relatedIds:key,important:i,type:"sellchance"});
        actions.doSearch();
    }

    markToCustomTag(lablestr,selectkey,type){   //应用  取消某标签
         const {actions} = this.props;
        actions.markToCustomTagType({relatedIds:selectkey,labelIds:lablestr,operationType:type,type:"sellchance"});
    }

    setting(){
        this.refs.setTagModal.visible = true
    }

    changeRightTab(key){
        const {actions} =this.props;
        actions.setRightTabKey(key);
    }
    dateSelectChange(val){
        const {actions,rightTabKey} = this.props;
        actions.saveSelectValue(val);
        if(rightTabKey == "1"){actions.getContactLogs({datatype:val});}
        if(rightTabKey == "2"){actions.getContacterCard({datatype:val});}
    }
    getTabButtonsAd() {
    	const {actions} = this.props;
        return [
            (<Button type="primary" onClick={()=>{actions.doSearch();actions.setShowSearchAd(false)}}>搜索</Button>),
            (<Button type="ghost" onClick={()=>{actions.saveOrderFields({})}}>重置</Button>),
            (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
        ]
    }
}







class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

SellChanceMain = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(SellChanceMain);

SellChanceMain = createForm({
	onFieldsChange(props, fields) {
        props.actions.saveOrderFields({...props.orderFields.toJS(), ...fields});
    },
	mapPropsToFields(props) {
		return props.orderFields.toJS();
  	}
})(SellChanceMain);

function mapStateToProps(state) {
    // return {...state.crmContactQuery}
	const {crmsellChanceMain,comsWeaTable} = state;
    return {
    	loading: crmsellChanceMain.get('loading'),
        title: crmsellChanceMain.get('title'),
        dataKey:crmsellChanceMain.get('dataKey'),
        conditioninfo: crmsellChanceMain.get('conditioninfo'),
        detailTabKey: crmsellChanceMain.get('detailTabKey'),
        searchParamsAd: crmsellChanceMain.get('searchParamsAd'),
        showSearchAd:crmsellChanceMain.get('showSearchAd'),
        orderFields: crmsellChanceMain.get('orderFields'),
        sellChanceStatus:crmsellChanceMain.get('sellChanceStatus'),
        tabDatas:crmsellChanceMain.get('tabDatas'),
        hrmList:crmsellChanceMain.get('hrmList'),
        tagDatas:crmsellChanceMain.get('tagDatas'),
        viewTypeList:crmsellChanceMain.get('viewTypeList'),
        istorefresh:crmsellChanceMain.get('istorefresh'),
        detailTabDatas:crmsellChanceMain.get('detailTabDatas'),
        rightTabKey:crmsellChanceMain.get('rightTabKey'),
        selectValue:crmsellChanceMain.get('selectValue'),
        contactLogs:crmsellChanceMain.get('contactLogs'),
        cardloading:crmsellChanceMain.get('cardloading'),
        contacterCard:crmsellChanceMain.get('contacterCard'),
        rightInfos:crmsellChanceMain.get('rightInfos'),
        showRight:crmsellChanceMain.get('showRight'),
        remindCount:crmsellChanceMain.get('remindCount'),
        //table
        comsWeaTable: comsWeaTable, //绑定整个table
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...SellChanceMainAction,...WeaTableAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(SellChanceMain);
